@(user: String, host: Boolean, ready: Boolean, started: Boolean)

$(function() {
    var WS = window['MozWebSocket'] ? MozWebSocket : WebSocket
    var Socket = new WS("@routes.Application.connect(user).webSocketURL(request)")
    var User = "";
    
    var PlayersNumber = 1;
    var BotsNumber = 1;
    var Total = PlayersNumber+BotsNumber;
    var StartTokens = 300;
    var Ante = 20;
	
	var OtherPlayers = new Array(3);
    
	var Cards = new Array(4);
	var Selected = new Array(5);
	var SelectedCards = 0;
	var LastAction = [0,0,0,0];
	var CurrentBet = [0,0,0,0];
	var CurrentPot = [0,0,0,0];
	var PlayerTokens = [StartTokens,StartTokens,StartTokens,StartTokens];
	
	var MyTurn = false;
	var GameStatus = 0;
	var Ability = 0;
	
	var GS_STOPPED = 0;
	var GS_FIRST_BETTING = 1;
	var GS_REPLACING = 2;
	var GS_SECOND_BETTING = 3;
	var GS_SUMUP = 4;
	
	function GetGameStatus(GS) {
	
		if ( GS == GS_STOPPED ) return "Game stopped!";
		if ( GS == GS_FIRST_BETTING ) return "First betting!";
		if ( GS == GS_REPLACING ) return "Exchanging cards!";
		if ( GS == GS_SECOND_BETTING ) return "Second betting!";
		if ( GS == GS_SUMUP ) return "Sumup!";
	}
	
	var AB_NONE = 0;
	var AB_CHECKBETFOLD = 1;
	var AB_RAISECALLFOLD = 2;
	var AB_FOLDALLIN = 3;
	var AB_REPLACE = 4;
	var AB_CONFIRM = 5;
	
	function GetAbility(AB) {
	
		if ( AB == AB_NONE ) return "No rights!";
		if ( AB == AB_CHECKBETFOLD ) return "Check, bet or fold!";
		if ( AB == AB_RAISECALLFOLD ) return "Raise, call or fold!";
		if ( AB == AB_FOLDALLIN ) return "Fold or all-in!";
		if ( AB == AB_REPLACE ) return "Replace!";
		if ( AB == AB_CONFIRM ) return "Confirm!";
	}
	
	var MO_FOLD = 0;
	var MO_BET = 1;
	var MO_CHECK = 2;
	var MO_RAISE = 3;
	var MO_CALL = 4;
	var MO_ALLIN = 5;
	var MO_REPLACE = 6;
	var MO_READY = 7;
	
	function GetAction(AC) {
	
		if ( AC == MO_FOLD ) return "folds";
		if ( AC == MO_BET ) return "bets";
		if ( AC == MO_CHECK ) return "checks";
		if ( AC == MO_RAISE ) return "raises";
		if ( AC == MO_CALL ) return "calls";
		if ( AC == MO_ALLIN ) return "goes all-in";
		if ( AC == MO_REPLACE ) return "replaces cards";
		if ( AC == MO_READY ) return "is ready";
	}
	
	var CardIterator = [0,0,0,0];
	
	for (var i=0; i<4; i++) {
		Cards[i] = new Array(5);
		OtherPlayers[i] = "";
	}
	
	for (var i=0; i<4; i++) {
		for (var j=0; j<5; j++)
			Cards[i][j] = 0;
	}
	
	function SetUserID(s) {
		for (var i = 0; i < 3; i++) {
			if ( OtherPlayers[i] == "" ) {
				OtherPlayers[i] = s;
				$( "#cards"+(i+1).toString() ).show();
				break;
			}	
		}
	}
	
	function GetUserID(s) {
		for (var i = 0; i < 3; i++) {
			if ( OtherPlayers[i] == s ) {
				return i;
			}	
		}
	}

	var sendMessage = function( field, value ) {
        Socket.send('{"'+field+'":"'+value+'"}')
    }
    
    var receiveEvent = function(event) {
    
    	var data = JSON.parse(event.data);

        // Handle errors
        if(data.error) {
            Socket.close()
            return
        } else {
            $("#messages").show()
    	}
    	
    	var key, keys = [];

		for (key in data) {
  			if (data.hasOwnProperty(key))
    		keys.push(key)
		}
		
		for (var i=0; i<keys.length; i++) {
		
			if ( key == 'username' ) {
				User = data[key];
				$( "#game" ).hide();
			}
			else
			if ( key == 'game_status' ) {
	    		if ( data[key] == 'game_created' ) 
	    		{
	    			$( "#create" ).hide();
	    			$( "#settings" ).hide();		
	    			
	    			if ( @host == false ) {
	    				$( "#header" ).text("The game is ready, join in!");
	    				$( "#join" ).show();
	    			}
	    			else
	    			{
	    				$( "#header" ).text("The game is ready, waiting for players ...");
	    				
	    				$( "#parameters" ).show();
	    			
	    				$( "#parameters" ).html("Players: "+PlayersNumber.toString()+"<br>"+"Bots: "+BotsNumber.toString()+"<br>"+"Starting tokens: "+StartTokens.toString()+"<br>"+"Ante: "+Ante.toString()+"<br>");
	    			}
	    			
	    			fAppendToLog("New game has been created!");
	    		}
	    		else
	    		if ( data[key] == 'game_started' ) 
	    		{
	    			$( "#staging" ).hide();
	    			$( "#game" ).show();
					
	    			UpdateMyCards();
					UpdateMyBets();
	    			
	    			fAppendToLog("All ready! Game started!");
	    		}
	    		else
	    		if ( data[key] == 'game_stopped' ) 
	    		{
	    			$( "#staging" ).hide();
	    			$( "#game" ).hide();
	    			
	    			//fAppendToLog("Game stopped! Ouch ...");
	    		}
				else
	    		if ( data[key] == 'game_end' ) 
	    		{
					$( "#staging" ).hide();
	    			$( "#game" ).hide();
					$( "#summary" ).show();
					
	    			fAppendToLog("Game finished!");
	    		}
				
			}
			else
			if ( key == 'game_joined' ) {

				if ( User == data[key] )
				{
	    			$( "#join" ).hide();		
	    			$( "#header" ).text("The game is ready, waiting for players ...");
	    		}
	    		else
	    		{
	    			
	    		}
	    		
	    		fAppendToLog(data[key]+" joined the game!");
			}
			else
			if ( key == 'game_left' ) {

				if ( User == data[key] )
				{

	    		}
	    		else
	    		{
	    			for (var i = 0; i < 3; i++) {
						if ( OtherPlayers[i] == data[key] ) {
							OtherPlayers[i] = "";
							$( "#cards"+(i+1).toString() ).hide();
							$( "#bets"+(i+1).toString() ).hide();
							break;
						}	
					}
	    		}
	    		
	    		fAppendToLog(data[key]+" left the game!");
	    		
			}
			else
			if ( key == 'game_summary' ) {
				
				var Summary = data[key];
				
				$( "#summarytext" ).html(Summary);
			}
			else
			if ( key == 'send_player' ) {
			
				if ( User == data[key] )
				{
				
				}
				else
				{
					SetUserID(data[key]);
					var id = GetUserID(data[key]);
					$( "#name"+(id+1).toString() ).html("Player: "+data[key]+" cards");
				}
			}
			else
			if ( keys[i] == 'send_card' ) {
			
				//var data_ = JSON.parse(data);
				
				if ( User == data[keys[i]] )
				{
					var CardID = data[keys[i+1]];
					Cards[0][CardIterator[0]] = parseInt(CardID);
					CardIterator[0]++;
					if (CardIterator[0]>4) CardIterator[0]=0;
					
					UpdateMyCards();
					//fAppendToLog("You have received card from the server!");
				}
				else
				{
					var id = GetUserID(data[keys[i]]);
					var CardID = data[keys[i+1]];
					
					Cards[id+1][CardIterator[id+1]] = parseInt(CardID);
					CardIterator[id+1]++;
					if (CardIterator[id+1]>4) CardIterator[id+1]=0;
					
					UpdateOtherCards(id);
					//fAppendToLog((id+1).toString()+" have received card - "+CardID);
				}
				
			}
			else
			if ( keys[i] == 'send_info' ) {
			
				//var data_ = JSON.parse(data);
				
				if ( User == data[keys[i]] )
				{
					LastAction[0] = parseInt(data[keys[i+1]]);
					CurrentBet[0] = parseInt(data[keys[i+2]]);
					CurrentPot[0] = parseInt(data[keys[i+3]]);
					PlayerTokens[0] = parseInt(data[keys[i+4]]);
					
					//alert(LastAction[0].toString());
					UpdateMyBets();
					
					//fAppendToLog("You "+GetAction(LastAction[0]));
				}
				else
				{
					var id = GetUserID(data[keys[i]]);
					
					LastAction[id+1] = parseInt(data[keys[i+1]]);
					CurrentBet[id+1] = parseInt(data[keys[i+2]]);
					CurrentPot[id+1] = parseInt(data[keys[i+3]]);
					PlayerTokens[id+1] = parseInt(data[keys[i+4]]);
					
					UpdateOtherBets(id);
				}
				
			}
			else
			if ( key == 'new_turn' ) {
			
				if ( User == data[key] )
				{
					MyTurn = true;
					ResetCards();
					fAppendToLog("It's your turn "+User+"!");
				}
				else
				{
					MyTurn = false;
					HideActionsPanel();
					ResetCards();
					fAppendToLog(data[key]+"'s turn!");
				}
			}
			else
			if ( key == 'turn_status' ) {
				var GetStatus = parseInt(data[key]);
				HideSumUp();
				
				if ( GameStatus != GetStatus ) 
					fAppendToLog("Current game status - "+GetGameStatus(GetStatus));
					
				GameStatus = GetStatus;
			}
			else
			if ( key == 'turn_ability' ) {
				Ability = parseInt(data[key]);
				UpdateActionsPanel(Ability);
				fAppendToLog("Your abilities in this turn - "+GetAbility(Ability));
			}
			else
			if ( key == 'send_sumup' ) {
				var SumupMessage = data[key];
				
				ShowSumUp(SumupMessage);
				fAppendToLog("End of turn - sumup!");
			}
			else
			if ( keys[i] == 'send_action' ) {
			
				
				if ( User == data[keys[i]] )
				{
				
					//fAppendToLog("It's your turn "+User+"!");
				}
				else
				{
					var action = parseInt(data[keys[i+1]]);
					var id = GetUserID(data[keys[i]]);
					//alert(data[keys[i]]);
					if ( action == MO_BET || action == MO_RAISE ) {
						var value = data[keys[i+2]];
						fAppendToLog(data[keys[i]]+" "+GetAction(action)+": "+value.toString()+"!");
					}
					else
						fAppendToLog(data[keys[i]]+" "+GetAction(action)+"!");
				}
			}
			else
			if ( key == 'remove' ) {

				if ( User == data[key] )
				{
					Socket.close();
					
					$( "#join" ).hide();		
	    			$( "#header" ).text("The game is full ...");
					//location.reload();
	    		}
	    		else
	    		{
	    			
	    		}
	    		
	    		fAppendToLog("You have been removed from the game!");
			}
			else
			if ( key == 'message' ) {
				fAppendToLog(data[key]);
	    	}
			else 
			if ( key == 'game_error' ) {
				alert(data[key]);
			}
		}
   
    }
    
    if ( @started == false ) 
    {
    	$( "#parameters" ).hide();
    	$( "#create" ).hide();
    	$( "#settings" ).hide();
    	
    	if ( @host == true ) {

    		if ( @ready == false ) {
    			$( "#header" ).text("You are the host, create a new game!");
    			$( "#create" ).show();
    			$( "#join" ).hide();
    			$( "#settings" ).show();
    		}
    	}
    	else
    	{	
    		if ( @ready == false ) {
    			$( "#header" ).text("Please wait, host is configuring a new game ...");
    			$( "#join" ).hide();
    		}
    		else
    		{
    			$( "#header" ).text("The game is ready, join in!");
    			$( "#join" ).show();
    		}
    	}	
    }
    
    
    $( "#create" ).on( "click", fNewGame );
    $( "#join" ).on( "click", fJoinGame );
	$( ".mycard" ).on( "click", function() { 
		var a = $(this).attr("alt");

	if ( MyTurn && Ability == AB_REPLACE && GameStatus == GS_REPLACING )
	{
		if ( a == 'N' )
		{
			if ( SelectedCards < 4 ) {
				SelectedCards++;
				$(this).attr("alt",'S');
				$(this).css('position', 'relative'); 
				$(this).css('top', '-20px'); 
			}
		}
		else
		{
			SelectedCards--;
			$(this).attr("alt",'N');
			$(this).css('position', 'relative'); 
			$(this).css('top', '0px'); 
		}
	}
	} );
	$( "#fold" ).on( "click", fFold );
	$( "#bet" ).on( "click", fBet );
	$( "#check" ).on( "click", fCheck );
	$( "#raise" ).on( "click", fRaise );
	$( "#call" ).on( "click", fCall );
	$( "#allin" ).on( "click", fAllin );
	$( "#replace" ).on( "click", fReplace );
	$( "#confirm" ).on( "click", fConfirm );
	$( "#end" ).on( "click", fEnd );
	
	function fConfirm() {
    	sendMessage("action","confirm");
    }
	
	function fEnd() {
    	window.location = "@routes.Application.quit(user)";
    }
	
	function fFold() {
    	sendMessage("action","fold");
    }
	
	function fCheck() {
    	sendMessage("action","check");
    }
	
	function fCall() {
    	sendMessage("action","call");
    }
	
	function fAllin() {
    	sendMessage("action","allin");
    }
	
	function fReplace() {
		var replace = new Array(5);
		var a;
		
		for (var i=0; i<5; i++) {
		
			a = $( "#card"+i.toString() ).attr("alt");

			if ( a == 'S' ) 
				replace[i] = Cards[0][i].toString();
			else
				replace[i] = "0";
		}
		
    	Socket.send('{"action":"replace","card0":"'+replace[0]+'","card1":"'+replace[1]+'","card2":"'+replace[2]+'","card3":"'+replace[3]+'","card4":"'+replace[4]+'"}')
    }
	
	function fBet() {
	
		var YourBet = $( "#betval" ).val();
    	Socket.send('{"action":"bet","amount":"'+YourBet+'"}')
    }
	
	function fRaise() {
	
    	var YourBet = $( "#raiseval" ).val();
    	Socket.send('{"action":"raise","amount":"'+YourBet+'"}')
    }
    
    function fNewGame() {
    
    	PlayersNumber = $("#players").val();
    	BotsNumber = $("#bots").val();
    	StartTokens = $("#tokens").val();
    	Ante = $("#ante").val();
    	
    	Socket.send('{"action":"new_game","settings_players":"'+PlayersNumber+'","settings_bots":"'+BotsNumber+'","settings_tokens":"'+StartTokens+'","settings_ante":"'+Ante+'"}')
    }
    
    function fJoinGame() {
    	sendMessage("action","join_game");
    }
    
    function fAppendToLog(m) {
    	var el = $('<div class="message"><p style="font-size:12px"></p></div>')
	    $("p", el).text("LOG ->"+m)
	    $(el).addClass('me')
	    $('#messages').append(el)
		$('#messages').scrollTop = $('#messages').scrollHeight;
	}
	
	function HideActionsPanel() {
	
		$( "#fold" ).hide();
		$( "#bet" ).hide();
		$( "#betval" ).hide();
		$( "#raiseval" ).hide();
		$( "#check" ).hide();
		$( "#raise" ).hide();
		$( "#call" ).hide();
		$( "#allin" ).hide();
		$( "#replace" ).hide();
		$( "#confirm" ).hide();
		$( "#end" ).hide();
	}
	
	function ShowSumUp(s) {
		$( "#sumuptext" ).html(s);
		$( "#sumup" ).show();
		
		for (var i = 0; i < 3; i++) {
			if ( OtherPlayers[i] != "" ) {
				$( "#cards"+(1+i).toString() ).show();
			}	
		}
	}
	
	function HideSumUp() {
		$( "#sumup" ).hide();
		
		for (var j = 0; j < 3; j++) {
			if ( OtherPlayers[j] != "" ) {
				//$( "#cards"+(1+j).toString() ).hide();
				
				for (var i=0; i<5; i++) {
					$( "#card"+(i+(1+j)*5).toString() ).attr("src", "../assets/images/0.png");
				}
			}	
		}
	}
	
	function UpdateActionsPanel(ab) {
		
		$( "#fold" ).hide();
		$( "#bet" ).hide();
		$( "#betval" ).hide();
		$( "#raiseval" ).hide();
		$( "#check" ).hide();
		$( "#raise" ).hide();
		$( "#call" ).hide();
		$( "#allin" ).hide();
		$( "#replace" ).hide();
		$( "#confirm" ).hide();
		$( "#end" ).hide();
		
		if ( GameStatus != GS_STOPPED ) {
			
			if ( ab == AB_CHECKBETFOLD ) {
				$( "#fold" ).show();
				$( "#bet" ).show();
				$( "#betval" ).show();
				$( "#check" ).show();
				
				FillBetVal();
			}
			else
			if ( ab == AB_RAISECALLFOLD ) {
				$( "#fold" ).show();
				$( "#raise" ).show();
				$( "#raiseval" ).show();
				$( "#call" ).show();
				
				FillRaiseVal();
			}
			else
			if ( ab == AB_FOLDALLIN ) {
				$( "#fold" ).show();
				$( "#allin" ).show();
			}
			else
			if ( ab == AB_REPLACE ) {
				$( "#replace" ).show();
			}
			else
			if ( ab == AB_CONFIRM ) {
				$( "#confirm" ).show();
			}
		}
		else
		{
			$( "#end" ).show();
		}
	}
	
	function FillBetVal() {
		
		$( "#betval" ).val("1");
	}
	
	function FillRaiseVal() {
	
		var maxBet = 0;
		
		for (var i=0; i<3; i++) {
			if ( CurrentPot[i+1] > maxBet ) 
				maxBet = CurrentPot[i+1];
		}
		
		var RaiseVal = maxBet - CurrentPot[0];
		
		$( "#raiseval" ).val((RaiseVal+1).toString());
	}
	
	function ResetCards() {
	
		SelectedCards = 0;
		
		for (var i=0; i<5; i++) {
			$( "#card"+i.toString() ).attr("alt", "N");
			$( "#card"+i.toString() ).css('position', 'relative'); 
			$( "#card"+i.toString() ).css('top', '0px');
		}
	}
	
	function UpdateMyCards() {
	
		for (var i=0; i<5; i++) {
			$( "#card"+i.toString() ).attr("src", "../assets/images/"+(Cards[0][i]).toString()+".png");
		}
	}
	
	function UpdateMyBets() {
		$( "#bets0" ).html("<strong>Player: "+User+"</strong><br>Last action: "+GetAction(LastAction[0])+"<br>Last bet: "+CurrentBet[0].toString()+"<br>Total bet: "+CurrentPot[0].toString()+"<br>Tokens: "+PlayerTokens[0].toString()+"<br>");
	}
	
	function UpdateOtherCards(id) {

		for (var i=0; i<5; i++) {
			//fAppendToLog("Card "+(i+(1+id)*5).toString()+": "+(Cards[id+1][i]).toString());
			$( "#card"+(i+(1+id)*5).toString() ).attr("src", "../assets/images/"+(Cards[id+1][i]).toString()+".png");
		}
	}
	
	function UpdateOtherBets(id) {
		//alert((id+1).toString());
		$( "#bets"+(id+1).toString() ).html("<strong>Player: "+OtherPlayers[id]+"</strong><br>Last action: "+GetAction(LastAction[id+1])+"<br>Last bet: "+CurrentBet[id+1].toString()+"<br>Total bet: "+CurrentPot[id+1].toString()+"<br>Tokens: "+PlayerTokens[id+1].toString()+"<br>");
	}

    Socket.onmessage = receiveEvent;
    Socket.onclose = location.reload;
})
